
package net.swa.dewei.service.impl;

import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Service;
import net.swa.dewei.beans.entity.Advertisement;
import net.swa.dewei.service.AdService;
import net.swa.system.dao.HibernateDaoSupport;
import net.swa.util.JsonResult;

@Service("adService")
public class AdServiceImpl extends HibernateDaoSupport implements AdService
{

    @Override
    public Advertisement queryById(Long id)
    {
        Advertisement m = null;
        Session session = getCurrentSession();
        m = (Advertisement) session.get(Advertisement.class, id);
        return m;
    }

    @Override
    public JsonResult<Advertisement> queryPage(String[] attrNames , String[] attrOperator , Object[] attrValues ,
            int currentPage , int pageSize , String orderBy , String orderType)
    {
        JsonResult<Advertisement> json = new JsonResult<Advertisement>();
        List<Advertisement> list = new ArrayList<Advertisement>();
        StringBuilder hql = new StringBuilder();
        hql.append("from Advertisement where 1=1 ");
        for (int i = 0; i < attrNames.length; i++)
        {
            String operator = attrOperator[i];
            if (!StringUtils.isEmpty(operator))
            {
                operator = operator.replace("'", "");
                String val = attrValues[i] == null ? "" : attrValues[i].toString();
                if (val.indexOf("||") > 0)
                {
                    String[] vals = val.split("\\|\\|");
                    hql.append(" and (");
                    for (int j = 0; j < vals.length; j++)
                    {
                        hql.append((j == 0 ? "" : " or ") + attrNames[i] + operator + " :param" + i + j);
                    }
                    hql.append(") ");
                }
                else
                {
                    if (attrValues[i] != null && !StringUtils.isBlank(attrValues[i].toString()))
                    {
                        hql.append(" and " + attrNames[i] + " " + operator + " :param" + i);
                    }
                }
            }
        }
        if (!StringUtils.isEmpty(orderBy))
        {
            hql.append(" order by " + orderBy + " " + orderType);
        }
        Query query = getCurrentSession().createQuery(hql.toString());
        for (int i = 0; i < attrValues.length; i++)
        {
            String val = attrValues[i] == null ? "" : attrValues[i].toString();
            if (val.indexOf("||") > 0)
            {
                String[] vals = val.split("\\|\\|");
                for (int j = 0; j < vals.length; j++)
                {
                    query.setString("param" + i + j, vals[j]);
                }
            }
            else
            {
                if (attrValues[i] != null && !StringUtils.isBlank(attrValues[i].toString()))
                {
                    String str = attrValues[i].toString();
                    if ("like".equalsIgnoreCase(attrOperator[i]))
                    {
                        str = "%" + str.trim() + "%";
                    }
                    query.setString("param" + i, str);
                }
            }
        }
        if (pageSize > 0)
        {
            int from = (currentPage - 1) * pageSize;
            query.setFirstResult(from);
            query.setMaxResults(pageSize);
        }
        list = query.list();
        // 查询满足条件的总数量
        query = getCurrentSession().createQuery("select count(*) " + hql);
        for (int i = 0; i < attrValues.length; i++)
        {
            String val = attrValues[i] == null ? "" : attrValues[i].toString();
            if (val.indexOf("||") > 0)
            {
                String[] vals = val.split("\\|\\|");
                for (int j = 0; j < vals.length; j++)
                {
                    query.setString("param" + i + j, vals[j]);
                }
            }
            else
            {
                if (attrValues[i] != null && !StringUtils.isBlank(attrValues[i].toString()))
                {
                    String str = attrValues[i].toString();
                    if ("like".equalsIgnoreCase(attrOperator[i]))
                    {
                        str = "%" + str.trim() + "%";
                    }
                    query.setString("param" + i, str);
                }
            }
        }
        if (pageSize > 0)
        {
            int totalCount = ((Number) (query.iterate().next())).intValue();
            int totalPage = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
            json.setTotalSize(totalCount);
            json.setTotalPage(totalPage);
            json.setPageSize(pageSize);
            json.setCurrentPage(currentPage);
        }

        json.setResult(list);
        return json;
    }

    @Override
    public boolean add(Advertisement model)
    {
        if (null != model)
        {
            Session session = getCurrentSession();
            session.save(model);
            return true;
        }
        else
        {
            return false;
        }

    }

    @Override
    public boolean update(Advertisement model)
    {
        if (model != null)
        {
            if (model.getId() != null)
            {
                Session session = getCurrentSession();
                session.update(model);
                return true;
            }
        }
        return false;
    }

    @Override
    public void delete(Long[] ids)
    {
        if (null != ids && ids.length > 0)
        {
            String hql = "delete from Advertisement where id=:id";
            Session session = getCurrentSession();
            Query q = session.createQuery(hql);
            for (Long id : ids)
            {
                q.setLong("id", id);
                q.executeUpdate();
            }
        }
    }

}